import SIdentify from '@/components/SIdentify'

export default {
    data() {
        // 多个校验,较为复杂的校验,通过validator在data里return前定义一个校验
        // 手机号或座机号规则
        let validatorTel = function (rule, value, callback) {
            if (!value) {
                return callback(new Error('电话不能为空！'))
            }
            let isTel = /^(0\d{2,3}-){0,1}\d{6,8}$/.test(value)
            let isMobile = /^1[34578]\d{9}$/.test(value)
            if (isTel || isMobile) {
                callback()
            } else {
                callback(new Error('请输入正确的电话！'))
            }
        }
        // 用户名规则
        let validatorName = function (rule, value, callback) {
            if (!value) {
                return callback(new Error('用户名不能为空！'))
            }
            let isName = /^[\u4E00-\u9FA5A-Za-z0-9_]+$/.test(value)
            if (isName) {
                callback()
            } else {
                callback(new Error('请输入正确的用户名！'))
            }
        }
        // 密码规则
        let validatorPwd = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'))
            } else {
                callback()
            }
        }
        // 重复密码规则
        let validatorRePwd = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.register_userInfo.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        // 验证码规则
        let validatorCode = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('验证码不能为空'))
                this.refreshCode()
            } else if (this.login_userInfo.code !== this.identifyCode) {
                callback(new Error('请填写正确验证码!'))
                this.refreshCode()
            } else {
                callback()
            }
        }
        return {
            identifyCode: '',
            identifyCodes: '1234567890abcdefjhijklinopqrsduvwxyz',

            // 数据绑定对象
            // 用户登录信息
            login_userInfo: {
                username: "",
                password: "",
                code: "",
            },
            // 用户注册信息
            register_userInfo: {
                userName: "",
                phone: "",
                password: "",
                repassword: "",
            },
            // 登录规则
            loginRules: {
                username: [
                    // 失去焦点时，校验是否有值，如果没有会有校验提示
                    { required: true, message: '用户名不能为空！', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '密码不能为空！', trigger: 'blur' },
                    // 失去焦点时，校验长度的最小值最大值，如果不符合有校验提示
                    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
                ],
                code: [
                    { validator: validatorCode, required: true, trigger: 'blur' },
                ]
            },
            // 注册规则
            registerRules: {
                userName: [
                    // 多个校验或复杂教育
                    // validator: validatorName,通过validator定义一个校验，校验的规则在validatorName里面
                    { validator: validatorName, required: true, trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码！', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
                    { validator: validatorPwd, required: true, trigger: 'blur' }
                ],
                repassword: [
                    { required: true, message: '请确认密码！', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
                    { validator: validatorRePwd, required: true, trigger: 'blur' }
                ],
                phone: [
                    { validator: validatorTel, required: true, trigger: 'blur' },
                ]
            },

            // cover样式
            cover: {
                transform: ''
            }
        }
    },
    components: {
        SIdentify
    },
    methods: {
        // 刷新验证码
        refreshCode() {
            this.identifyCode = ''
            this.makeCode(this.identifyCodes, 4)
        },
        makeCode(o, l) {
            for (let i = 0; i < l; i++) {
                this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]
            }
        },
        randomNum(min, max) {
            return Math.floor(Math.random() * (max - min) + min)
        },

        // 注册通道
        toregister() {
            const that = this
            this.cover.transform = 'translateX(-98%)'
            this.resetLoginFrom(that)
        },

        //登录通道
        returnLogin() {
            const that = this
            this.cover.transform = 'translateX(0%)'
            this.resetRegisterFrom(that)
        },

        // // 密码找回
        // toFind() {
        //     // 路由传值
        //     this.$router.push('/findPwd')
        // },

        // 重置登录表单信息
        resetLoginFrom(that) {
            // resetFields：对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
            that.$refs.loginFormRef.resetFields()
        },

        // 重置注册表单信息
        resetRegisterFrom(that) {
            // resetFields：对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
            that.$refs.registerFormRef.resetFields()
        },

        login() {
            // 表单预验证
            this.$refs.loginFormRef.validate(async valid => {
                const that = this
                // 验证不通过
                if (!valid) {
                    // 调用错误提示,重置表单信息
                    this.$store.commit("error", "登录信息不合法或验证码错误！请重新输入")
                    this.resetLoginFrom(that)
                    return
                } else {
                    // QS模块转化
                    const login_userInfo = this.$qs.stringify(this.login_userInfo)

                    // 发送post请求
                    const { data: res } = await this.$http.post('/gim/api/user/login', login_userInfo)
                    // console.log(res)
                    // 登录成功
                    if (res.code == 1) {
                        // token保存到客户端的sessionStorage中
                        window.sessionStorage.setItem('token', res.response.token)
                        this.$router.push("/admin")
                    } else {
                        // 调用错误消息提示
                        this.$store.commit("error", "登录失败！用户名或密码错误请重新输入！")
                        this.resetLoginFrom(that)
                    }
                }
                this.refreshCode()
            })
        },

        register() {
            // 表单预验证
            this.$refs.registerFormRef.validate(async valid => {
                const that = this
                //验证不成功
                if (!valid) {
                    // 调用错误提示,重置表单信息
                    this.$store.commit("error", "注册信息不合法或为空！请重新输入！")
                    this.resetRegisterFrom(that)
                    return
                } else {
                    //     QS模块转化
                    //     将form表单数据转化为Json
                    const register_userInfo = this.$qs.parse(this.register_userInfo)

                    // 发送post请求
                    const { data: res } = await this.$http.post('/gim/api/user/register', register_userInfo)
                    // console.log(res)
                    //注册成功
                    if (res.code == 1) {
                        // alert(111)
                        this.$store.commit("success", "注册成功！欢迎新用户！")
                        this.returnLogin()
                    } else {
                        this.$store.commit("error", "注册失败！用户名或电话号码已注册！请重新输入！")
                        this.resetRegisterFrom(that)
                    }
                }
            })
        },
    },
    mounted() {
        // 初始化验证码
        this.identifyCode = ''
        this.makeCode(this.identifyCodes, 4)
    },
}